﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;

namespace UploadFileMVCWebApplication.Controllers
{
    public class FileUploadController : Controller
    {
        private readonly IWebHostEnvironment _hostEnvironment;
        private readonly string _uploadDirectory;

        public FileUploadController(IWebHostEnvironment hostEnvironment)
        {
            _hostEnvironment = hostEnvironment;
            _uploadDirectory = Path.Combine(_hostEnvironment.WebRootPath, "uploads");

            if (!Directory.Exists(_uploadDirectory))
                Directory.CreateDirectory(_uploadDirectory);
        }

        // 显示上传页面
        public IActionResult Index()
        {
            return View();
        }

        // 处理多文件上传
        [HttpPost]
        [RequestSizeLimit(long.MaxValue)] // 取消请求大小限制（根据需求调整）
        public async Task<IActionResult> Upload(IEnumerable<IFormFile> files)
        {
            // 验证是否有文件
            if (files == null || !files.Any())
                return BadRequest("请选择文件");

            var uploadResults = new List<object>();

            foreach (var file in files)
            {
                // 验证单个文件是否有效
                if (file == null || file.Length == 0)
                {
                    ModelState.AddModelError("", "存在空文件，已跳过");
                    continue;
                }

                try
                {
                    // 生成唯一文件名（避免重复）
                    var fileName = $"{Guid.NewGuid()}_{Path.GetFileName(file.FileName)}";
                    var filePath = Path.Combine(_uploadDirectory, fileName);

                    // 保存文件到服务器
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }

                    // 记录成功上传的文件信息
                    uploadResults.Add(new
                    {
                        OriginalName = file.FileName,
                        SavedName = fileName,
                        Size = FormatFileSize(file.Length),
                        UploadedAt = DateTime.Now,
                        DownloadUrl = Url.Action("Download", new { fileName = fileName })
                    });
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", $"文件 {file.FileName} 上传失败: {ex.Message}");
                }
            }

            // 返回上传结果（包含成功的文件和错误信息）
            if (uploadResults.Any() || ModelState.ErrorCount == 0)
            {
                return Ok(uploadResults); // 成功时返回文件数组
            }
            else
            {
                // 所有文件都失败时返回错误信息
                var errorMessage = string.Join("；", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));
                return BadRequest(errorMessage);
            }
        }

        // 下载文件
        public IActionResult Download(string fileName)
        {
            var filePath = Path.Combine(_uploadDirectory, fileName);

            if (!System.IO.File.Exists(filePath))
                return NotFound();

            var fileInfo = new FileInfo(filePath);
            var contentType = GetContentType(fileName);

            return PhysicalFile(filePath, contentType, fileInfo.Name);
        }

        // 辅助方法
        private string GetContentType(string fileName)
        {
            var provider = new FileExtensionContentTypeProvider();
            if (!provider.TryGetContentType(fileName, out string contentType))
            {
                contentType = "application/octet-stream";
            }
            return contentType;
        }

        private string FormatFileSize(long bytes)
        {
            string[] sizes = { "B", "KB", "MB", "GB", "TB" };
            double len = bytes;
            int order = 0;
            while (len >= 1024 && order < sizes.Length - 1)
            {
                order++;
                len /= 1024;
            }
            return $"{len:0.##} {sizes[order]}";
        }
    }
}
